Koa
From Koa introduction:
Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. Through leveraging generators Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable.
Requirements
Koa requires Node 7.6.0
or higher for async/await
syntax.
You can use older Node versions with Babel (see more about it at Koa installation section).
MongoDB version does not matter. We will use the latest one.
Environment
Node.js
If Node is not installed yet, you can download it here. If you are a lucky owner of Linux or macOS, package managers can be used - this method described here.
To check that the Node installation is correct, you can run the command:
1 | $ node --version |
That will print the Node version.
Also for NPM:
1 | $ npm --version |
Dependencies installation
Create directory where all the code will be located. Run terminal and open this directory.
Let’s initialize the package environment:
1 | $ npm init |
NPM will ask you a few questions. Type answers for package name of author.
1 | $ npm init |
You should see the package.json
file that NPM has created.
Install koa
:
1 | $ npm i koa |
Also we need something for requests routing. We will use a koa-router
- popular and full-featured package.
Another one - koa-logger
- for development logging.
1 | $ npm i koa-router koa-logger |
For database we will use a koa-mongo
driver.
1 | $ npm i koa-mongo |
MongoDB
About Mongo
MongoDB is a free and open-source cross-platform document-oriented database program. MongoDB realises a new approach to building databases: no tables, schemas, SQL-queries, foreign keys and other things connected with relational databases.
Installation
You can download MongoDB installer from here. There you can choose between Community and Enterprise versions.
After downloading you have to create a directory on your hard drive that will contain Mongo databases. By default, in Windows OS it is C:\data\db
, so if you use Windows, you have to create this directory. In Linux and MacOS it is /data/db.
If you need to use another path, you can use --dbpath
flag when server starts.
Starting the server
After creating the directory for databases you can start MongoDB server. It is a mongod
application in bin
directory. Start the command propmt in Windows or the terminal in Linux and use the following commands. For Windows (if MongoDB is loaded in C:\mongodb
):1
2cd c:\mongodb\bin
mongod
Command prompt will show you some service staff, for example, server localhost
is running on port 27017.
If your databases located in another directory (for example, d:\test\mongodb\data
), use the following command:1
C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data
After successful starting of the server, we can use mongo
shell to connect to databases. This file is located in …\mongodb\bin too:1
2cd c:\mongodb\bin
mongo
If the installation of Mongo and starting of the server were successful, the command prompt will be waiting for queries to DB.
By default, MongoDB does not use any methods of authorization to access the database. The developers of MongoDB think that the application must contain all the logic. Database is only needed for data storage and management. Therefore, in this article, a authorized connection will not be considered.
The database will be automatically created with the first insert query.
You can exit by typing ‘exit’.
Hello, World!
Create file app.js
and copy the next code. It’s a modified version of standart Koa example.
1 | const Koa = require('koa'); |
Now you can start the server:
1 | $ node app.js |
If the server has successfully started, open the browser and go to http://localhost:3000/
. You should see the Hello, World!
page. Also, try to type your name, for example, http://localhost:3000/Elisey
.
In your terminal you should see something like that:
1 | node app.js |
Let’s connect to the database.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 ;
//Require an appropriate module
const Mongo = require('koa-mongo');
// Use Mongo
app.use(Mongo());
//For empty GET-request
router.get('/', async (ctx) => {
//Find necessary document with "find" method in collection "first_collection"
const result = await ctx.mongo.db('test').collection('first_collection').find({ text: "Hello, world!" }).toArray();
//If there is no document, add it with "insert" method
if (result.length === 0)
ctx.mongo.db('test').collection('first_collection').insert({ text: "Hello, world!" });
var helloWorld = await ctx.mongo.db('test').collection('first_collection').find({ text: "Hello, world!" }).toArray();
ctx.body = helloWorld[0].text;
});
// Similary with "named" GET-requests
router.get('/:name', async (ctx) => {
const result = await ctx.mongo.db('test').collection('first_collection').find({ text: ctx.params.name }).toArray();
if (result.length === 0)
ctx.mongo.db('test').collection('first_collection').insert({ text: ctx.params.name });
var name = await ctx.mongo.db('test').collection('first_collection').find({ text: ctx.params.name }).toArray();
name = name[0].text;
ctx.body = `Hello, ${name}!\n`;
});
Save and restart the server to see the result.
References and useful links
- Node deps
- MongoDB
- Beginning MongoDB
- Building A Server-Side Application With Async Functions and Koa 2
- Koa examples
- Koa wiki - extend Koa functionality
- Awesome Node.js